package com.bsoft.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 基于雪花算法生成ID
 *
 * @author twj
 *
 * Twitter_Snowflake
 * SnowFlake的结构如下(每部分用-分开):
 * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
 * 1位标识，由于long基本类型在Java中是带符号的，最高位是符号位，正数是0，负数是1，所以id一般是正数，最高位是0<br>
 * 41位时间截(毫秒级)，注意，41位时间截不是存储当前时间的时间截，而是存储时间截的差值（当前时间截 - 开始时间截)
 * 得到的值），这里的的开始时间截，一般是我们的id生成器开始使用的时间，由我们程序来指定的（如下下面程序IdWorker类的startTime属性）。
 * 41位的时间截，可以使用69年，年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
 * 10位的数据机器位，可以部署在1024个节点，包括5位datacenterId和5位workerId<br>
 * 12位序列，毫秒内的计数，12位的计数顺序号支持每个节点每毫秒(同一机器，同一时间截)产生4096个ID序号<br>
 * 以上加起来刚好64位，为一个Long型。（1 + 41 + 10 + 12）<br>
 * SnowFlake的优点是，整体上按照时间自增排序，并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分)，并且效率较高，经测试，SnowFlake每秒能够产生26万ID左右。
 */
public final class SnowFlakeUtil {

    private final static int min_time_bits = 41;
    private final static int default_worker_bits = 10;
    private final static int default_sequence_bits = 12;
    /**开始日期*/
    private final static String default_epoch_date = "2022-01-01";

    // 24
    private final static int max_worker_sequence_bits = 64 - 1 - min_time_bits;
    private final static long ts_year = 1000L * 60 * 60 * 24 * 365;

    public final static int default_max_worker_id = getMaxWorkerId(default_worker_bits);

    private static int getMaxWorkerId(int worker_bits) { return (1 << worker_bits) - 1; }

    private final int workerBits;
    private final int sequenceBits;
    private final int timeBits;

    private final long epoch;
    private final int workerId;
    private int sequence = 0;

    private final int shiftTime;
    private final int shiftWorker;
    private final int sequenceMask;

    private final long tolerantClockBackTimestamp;
    private long lastTimestamp = -1L;

    public SnowFlakeUtil(int workerId, long tolerantClockBackTimestamp) {
        this(workerId, tolerantClockBackTimestamp, default_worker_bits, default_sequence_bits, default_epoch_date);
    }

    private SnowFlakeUtil(int workerId, long tolerantClockBackTimestamp, int workerBits, int sequenceBits, String epochDate) {
        this.tolerantClockBackTimestamp = tolerantClockBackTimestamp;
        this.workerId = workerId;
        int maxWorkerId = getMaxWorkerId(workerBits);
        if (this.workerId < 0 || this.workerId > maxWorkerId) {
            throw new IllegalArgumentException(logPrefix() + "WorkerId应为：0-" + maxWorkerId);
        }
        this.workerBits = workerBits;
        this.sequenceBits = sequenceBits;
        this.shiftTime = workerBits + sequenceBits;
        this.shiftWorker = sequenceBits;
        this.sequenceMask = ~(-1 << sequenceBits);
        this.timeBits = 64 - 1 - workerBits - sequenceBits;
        if (timeBits < min_time_bits) {
            throw new IllegalArgumentException(logPrefix() + "时间戳位数不应小于" + min_time_bits + "(实际" + timeBits
                    + "), workerBits与sequenceBits之和应<=" + max_worker_sequence_bits + ".");
        }
        try {
            epoch = new SimpleDateFormat("yyyy-MM-dd").parse(epochDate).getTime();
        } catch (ParseException e) {
            throw new IllegalArgumentException("计时起点日期不正确。");
        }
    }

    private String logPrefix() {
        return "[workerId:" + workerId + "] ";
    }

    /**
     * 获得下一个ID (该方法是线程安全的)
     */
    public synchronized Long nextId() {
        long timestamp = timeGen();
        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            // 等待
            boolean fixedByWait = true;
            long offset = lastTimestamp - timestamp;
            if (offset <= tolerantClockBackTimestamp && tolerantClockBackTimestamp > 0) {
                try {
                    // wait * 2
                    wait(tolerantClockBackTimestamp << 1);
                } catch (InterruptedException ignored) {
                }
                timestamp = timeGen();
                if (timestamp < lastTimestamp) {
                    fixedByWait = false;
                }
            }
            if (!fixedByWait) {
                throw new IllegalStateException(
                        logPrefix() + "节点时钟被回拨，不能生成唯一ID，回拨值=" + offset + "ms，" +
                                "当前时间=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp) + "。");
            }
        }

        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            // 毫秒内序列溢出
            if (sequence == 0) {
                // 阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else if (sequence != 0) {
            // 时间戳改变，毫秒内序列重置
            sequence = 0;
        }

        // 上次生成ID的时间截
        lastTimestamp = timestamp;

        // 移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - epoch) << shiftTime) | ((long) workerId << shiftWorker) | sequence;
    }

    /**
     * 阻塞到下一毫秒
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

}
